import React, { memo } from 'react';
import { useDeepCompareEffect } from 'ahooks';
import _ from 'lodash';
import moment from 'moment';
import { getDvaApp } from 'umi';

import { WeatherIcon } from '#/components/index.js';
import { HomeOutlined } from '#/utils/antdIcons.js';
import { HttpCode } from '#/utils/contacts.js';
import { OnHistory } from '#/utils/interactive.js';
import { cacheRequest } from '#/utils/request.js';
import { useTRState } from '#/utils/trHooks.jsx';
import styles from './index.less';

interface IObj {
  deptNum: string;
}

interface IAppProps extends IHomeButtonProps {
  onlyTimeWithWeather?: boolean;
  stationInfo: IObj;
}
interface IHomeButtonProps {
  style?: React.CSSProperties;
  handleEvent?: () => void;
  replacePath?: string;
  iconReactNode?: React.ReactNode;
}

interface IComp {
  stationInfo: IObj;
}
/**
 * @description: heder按钮 支持传入自定义icon
 * @param props
 * @returns
 */
const HomeButton: React.FunctionComponent<IHomeButtonProps> = (props) => {
  const { style, handleEvent, iconReactNode } = props;
  const initGlobalData =
    getDvaApp()?._store?.getState()?.global?.configure?.initGlobalData?.homeConfig ?? {};
  const { homePath = '', hasHomeButton } = initGlobalData || {};

  if (!hasHomeButton) {
    return null;
  }
  const _handleEvent = () => {
    if (handleEvent) {
      // 自定义事件
      handleEvent();
    } else {
      if (homePath.length) {
        OnHistory({
          path: homePath,
          openType: 0,
        });
      }
    }
  };
  return (
    <div className={styles.homeButton} style={style} onClick={_handleEvent}>
      {iconReactNode ? { iconReactNode } : <HomeOutlined className={styles.icon_home} />}
    </div>
  );
};

/**
 * @description: 天气组件
 * @param props
 * @returns
 */
const WeatherComp: React.FunctionComponent<IComp> = (props) => {
  const { stationInfo } = props;
  const [state, setState] = useTRState({
    weatherInfo: null,
  });

  const getBackstageWeather = (params: any) => {
    return cacheRequest(
      '/power/weather/listWeatherWithDeptByIds',
      {
        method: 'POST',
        data: params,
        ttl: 9000000,
      },
      {
        diffParams: true,
      },
    );
  };

  const getData = async (nums: string[] = []) => {
    const res = await getBackstageWeather({ nums }); //天气信息请求
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setState({ weatherInfo: res.weatherInfoList[0]?.now || {} });
    }
  };

  useDeepCompareEffect(() => {
    stationInfo?.deptNum?.length && getData([stationInfo?.deptNum]);
  }, [stationInfo]);

  if (_.isEmpty(state.weatherInfo) || _.isEmpty(stationInfo)) {
    return <div />;
  }

  return (
    <div className={styles.weather}>
      <WeatherIcon style={{ fontSize: '16px' }} id={state.weatherInfo?.cond_code} />
      <span className={styles.weatherDesc}>
        {state.weatherInfo?.cond_txt}
        {state.weatherInfo?.tmp}&#8451;
      </span>
    </div>
  );
};

const TimeWithWeather: React.FunctionComponent<IAppProps> = (props: IAppProps) => {
  const { stationInfo } = props;
  return (
    <div className={styles.timeWrap}>
      <div className={styles.time}>{moment(moment().startOf('day')).format('YYYY.MM.DD')}</div>
      <WeatherComp stationInfo={stationInfo} />
    </div>
  );
};

const isEqual = (prevProps: IAppProps, nextProps: IAppProps) => {
  return _.isEqual(prevProps, nextProps);
};
/**
 * @description: 头部组件
 * @param props
 * @returns
 */
const HeaderWithHome: React.FunctionComponent<IAppProps> = memo((props) => {
  const {
    onlyTimeWithWeather,
    stationInfo,
    style,
    handleEvent,
    replacePath = '',
    iconReactNode,
  } = props;

  const _renderRightHeader = () => {
    if (onlyTimeWithWeather) {
      return <TimeWithWeather stationInfo={stationInfo} />;
    }
    return <>{props.children}</>;
  };
  return (
    <header className={styles.homeHeader}>
      <HomeButton
        style={style}
        handleEvent={handleEvent}
        replacePath={replacePath}
        iconReactNode={iconReactNode}
      />
      <div className={styles.homeHeader_right}>{_renderRightHeader()}</div>
    </header>
  );
}, isEqual);

export { HeaderWithHome, WeatherComp, TimeWithWeather, HomeButton };
